import 'package:flutter/material.dart';
import 'package:wallpaper_app/api/mohu.dart';
import 'package:wallpaper_app/components/Images/image_list.dart';
import 'package:wallpaper_app/model/image_base.dart';

class MohuImgs extends StatefulWidget {
  final String type;
  const MohuImgs({super.key, required this.type});

  @override
  State<MohuImgs> createState() => _MohuImgsState();
}

class _MohuImgsState extends State<MohuImgs> {
  List<ImageBase> imgs = [];
  Set<String> imgUrls = <String>{};
  bool loading = false;

  void getImgs() async {
    setState(() {
      loading = true;
    });
    if (!mounted) return;
    var res = await mohuImgsApi(id: widget.type);
    if (res.data['code'] == 200 || res.data['code'] == '200') {
      for (var i = 0; i < res.data['pic'].length; i++) {
        ImageBase img = ImageBase(
            smallPath: res.data['pic'][i],
            largePath: res.data['pic'][i].replaceAll('mw690', 'large'),
            tags: '');
        // 判断是否存在
        if (!imgUrls.contains(img.smallPath)) {
          setState(() {
            imgUrls.add(img.smallPath);
            imgs.add(img);
          });
        }
      }
    }
    setState(() {
      loading = false;
    });
  }

  @override
  void initState() {
    super.initState();
    getImgs();
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context).colorScheme;
    return Scaffold(
        floatingActionButton: FloatingActionButton(
          mini: true,
          heroTag: null,
          onPressed: () {
            setState(() {
              imgs.clear();
              imgUrls.clear();
            });
            getImgs();
          },
          tooltip: '刷新',
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(50),
          ),
          child: Icon(
            Icons.refresh,
            color: theme.primary,
          ),
        ),
        body: ImageList(
            imageList: imgs,
            isLoading: loading,
            onImageBottomLoading: () {
              if (loading) return;
              getImgs();
            }));
  }
}
